package group.rober.runtime.kit;

import group.rober.runtime.lang.RoberException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Stack;

public abstract class ClassKit {
    protected static Logger logger = LoggerFactory.getLogger(ClassKit.class);
    public static Stack<ClassLoader> getClassLoaderStack(Class<?> startClass){
        Stack<ClassLoader> stack = new Stack<ClassLoader>();
        if(startClass != null){
            ClassLoader classLoader = startClass.getClassLoader();
            while(classLoader!=null){
                stack.push(classLoader);
                classLoader = classLoader.getParent();
            }
        }
        return stack;
    }

    public static Field getField(Class<?> classType,String fieldName){
        try {
            return classType.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            logger.warn(MessageFormat.format("{0}.{1}不存在",classType.getName(),fieldName));
        }
        return null;
    }

    public static URL getClassURL(Class<?> clazz){
        String className = clazz.getName();
        className = className.replace('.', '/');
        String resource = "/" + className + ".class";
        URL url = clazz.getResource(resource);
        return url;
    }

    public static Object newInstance(String className){
        try {
            return Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            throw new RoberException(e);
        } catch (IllegalAccessException e) {
            throw new RoberException(e);
        } catch (ClassNotFoundException e) {
            throw new RoberException(e);
        }
    }

}
